import router from "@/routers";
import { defineStore } from "pinia";
import { TabsState, TabsMenuProps } from "@/stores/interface";
import piniaPersistConfig from "@/config/piniaPersist";
import { useKeepAliveStore } from "./keepAlive";

const keepAliveStore = useKeepAliveStore();

export const useTabsStore = defineStore({
    id: 'beam-tabs',
    state: (): TabsState => ({
        tabsMenuList: []
    }),
    actions: {
        async addTabs(tabItem: TabsMenuProps) {
            if (this.tabsMenuList.every(item => item.path !== tabItem.path)) {
                this.tabsMenuList.push(tabItem)
            }
        },
        async removeTabs(tabPath: string, isCurrent: boolean = true) {
            const tabsMenuList = this.tabsMenuList
            if (isCurrent) {
                tabsMenuList.forEach((item, index) => {
                    if (item.path !== tabPath) return
                    const nextTab = tabsMenuList[index + 1] || tabsMenuList[index - 1]
                    if (!nextTab) return
                    router.push(nextTab.path)
                })
            }
            this.tabsMenuList = tabsMenuList.filter(item => item.path !== tabPath)
        },
        async setTabs(tabsMenuList: TabsMenuProps[]) {
            this.tabsMenuList = tabsMenuList;
        },
        // Close Tabs On Side
        async closeTabsOnSide(path: string, type: "left" | "right") {
            const currentIndex = this.tabsMenuList.findIndex(item => item.path === path);
            if (currentIndex !== -1) {
                const range = type === "left" ? [0, currentIndex] : [currentIndex + 1, this.tabsMenuList.length];
                this.tabsMenuList = this.tabsMenuList.filter((item, index) => {
                    return index < range[0] || index >= range[1] || !item.close;
                });
            }
            keepAliveStore.setKeepAliveName(this.tabsMenuList.map(item => item.name));
        },
        // Close MultipleTab
        async closeMultipleTab(tabsMenuValue?: string) {
            this.tabsMenuList = this.tabsMenuList.filter(item => {
                return item.path === tabsMenuValue || !item.close;
            });
            keepAliveStore.setKeepAliveName(this.tabsMenuList.map(item => item.name));
        },
    },
    persist: piniaPersistConfig("beam-tabs")
})